import { createRouter, createWebHashHistory, RouteRecordRaw } from 'vue-router'
import Main from '@/views/Main.vue'
import home from "@/views/home.vue"
import error from "@/views/error/error.vue"
import login from "@/views/login/login.vue"
import { dynamicRoutes } from "@/router/dynamicRoutes";

let arr:any = [];
if(localStorage.getItem('menus')) {
  // 如果有菜单列表，动态添加路由
  const menuList = JSON.parse(localStorage.getItem('menus') || '[]');
  
  menuList.forEach((item:any) => {
      if(!item.children || item.children.length === 0) {
          
          // 如果没有子菜单，直接添加路由
          let menuItem = {
              path: "/" + item.Name,
              name: item.Name,
              component: () => import(`@/views/${item.Href}.vue`)
          }
          // 添加路由
          console.log(menuItem)
          arr.push(menuItem)
      }else{
          // let menuItem = []
          item.children.forEach((child:any) => {
            console.log(`@/views/${child.Href}.vue`)
              let childItem = {
                  path: "/" + child.Name,
                  name: child.Name,
                  component: () => import(`@/views/${child.Href}.vue`)
              }
              arr.push(childItem)
          })
      }
  })
}


const routes: Array<RouteRecordRaw> = [
  {
    path: '/',
    name: 'ss_system',
    component: Main,
    redirect:"/home",
    children:[
      {
        path:'/home',
        name:'home',
        component:home
      },
      {
        path:'/error',
        name:'error',
        component:error
      },
      ...arr // 动态添加的路由
    ]
  },
  {
    path:'/login',
    name:'login',
    component:login
  },
  {
    path: "/:catchAll(.*)",
    redirect: '/error'
  }
]

console.log(routes)

const router = createRouter({
  history: createWebHashHistory(),
  routes
})

router.beforeEach(async (to, from, next ) => {
  // 如果访问的是登录页，直接放行
  if (to.name === 'login') {
    next();
  }
  // 如果没有登录，跳转到登录页
  const userInfo = localStorage.getItem('userInfo')
  if (!userInfo) {
    next({ name: 'login' })
  }
  // 如果有登录信息，放行
  next();
})



export default router

